package songZhao.MinaDemo.Example;

import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

public class ExampleProtocolEncoder  extends ProtocolEncoderAdapter{
	
	private final Charset charset;
	
	
	public ExampleProtocolEncoder(Charset charset) {
		this.charset = charset;
	}


	@Override
	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
		//这里这个报文,就是我们之前写的自定义协议报文.ProtocolPack
		ProtocolPack value = (ProtocolPack) message;
		IoBuffer buffer = IoBuffer.allocate(value.getLength(), false);
		buffer.setAutoExpand(true);
		/*写入报文的数据,到buffer缓冲区中.这里写的顺序和decoder的读顺序需要一致.
		 *这里将flag放到中间,确保字符串之后是个int
		 */
		buffer.putInt(value.getLength());
		buffer.put(value.getFlag());
		String temp = value.getContent();
		if (temp!=null) {
			buffer.put(temp.getBytes(charset));
		}
		buffer.flip();
		out.write(buffer);
		System.out.println(buffer.position()+":"+buffer.limit()+":"+buffer.capacity());
	}
}
